<?php

namespace app\admin\controller;
use app\common\controller\Admin;
use app\ads\controller\Api;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 书库
 *
 * @Author 小邓
 * @DateTime 2022-11-05
 */
class Book extends Admin {

    public $uploadDownTxt;
    public $book_id;
	public function _initialize() {
		parent::_initialize();
        $this->uploadDownTxt = new \app\admin\model\UploadDownTxt();
        $this->book_id   = input('get.book_id', 47);
    }

    //  书库
    // public function index(){
    //     return view();
    // }

    public function _empty(){
        $action    = ACTION_NAME;
        $cate_type = input('get.cate_type', 'baidu_text');
        $this->getUserList();//用户
        if(in_array($cate_type, ['baidu_text', 'douyin_text', 'weibo_text', 'img', 'video', 'bgm'])){
            $this->bookMaterial( $cate_type );
        }

        $params = request()->param();
        $bookList = db('ads_material_book')->order('name desc,sort desc,id asc')->limit(1000)->select();
        $book_id = empty($bookList) ? 47 : $bookList[key($bookList)]['id'];
        $book_id = isset($params['book_id']) ? $params['book_id'] : $book_id;

        // 文本列表
        $txtList = $this->getTxtLog($params);
        $txtLog = $txtList['list'];
        $txtPage = $txtList['page'];
        $this->assign(compact('txtLog', 'txtPage'));

        // 版本列表
        $replace = $this->getReplaceList($params);
        $replaceList = $replace['list'];
        $repPage = $replace['page'];
        $this->assign(compact('replaceList', 'repPage'));

        // 数据列表
        $datas = $this->getDataList($params);
        $dataList = $datas['list'];
        $dataPage = $datas['page'];
        $this->assign(compact('dataList', 'dataPage'));

        // 是否指定书籍 未指定则取列表第一本
        $txt_id = isset($params['txt_id']) ? $params['txt_id']  : 0;
        if ($txt_id == 0) {
            $txt_id = empty($txtLog) ? 0 : $txtLog[0]['id'];
        }

        // 有书籍id则返回指定章节、概要信息，有章节信息则返回第一节内容
        $synopsis = ''; // 概要
        $content = ''; // 默认内容
        $directory = [];
        $dirPage = [
            'dirTotal' => 0,
            'dirPage' => isset($params['dirPage']) ? $params['dirPage'] : 1,
            'limit' => isset($params['limit']) ? $params['limit'] : 40,
        ];
        $directory_id = isset($params['directory_id']) ? $params['directory_id']  : 0;
        if ($txt_id > 0) {
            $dirPage['dirTotal'] = db('ads_book_directory')->where('txt_id', $txt_id)->count('id');
            $directory = db('ads_book_directory')->order('sort', 'asc')->where('txt_id', $txt_id)->page($dirPage['dirPage'], $dirPage['limit'])->column('id,num,title,sort');
            $synopsis = db('upload_txt_log')->where('id', $txt_id)->value('synopsis');

            if ($directory_id == 0) {
                $directory_id = empty($directory) ? 0 : $directory[key($directory)]['id'];
            }
            if ($directory_id > 0) {
                $content = db('ads_book_directory')->where('txt_id', $txt_id)->where('id', $directory_id)->value('content');
            }
        }

        //版本内容
        $replaceContent = '';
        $replace_id = isset($params['replace_id']) ? $params['replace_id'] : 0;
        if ($replace_id == 0) {
            $replace_id = empty($replaceList) ? 0 : $replaceList[0]['id'];
        }
        if ($replace_id > 0) {
            $replaceContent = db('replace_log')->where('id', $replace_id)->value('content');
        }

        $this->assign(compact('action', 'cate_type', 'book_id', 'bookList', 'directory', 'txt_id',
            'synopsis','content', 'directory_id', 'dirPage', 'replaceContent','replace_id'));
        return view('book/'.$action );
    }

    /**
     * Notes: 数据列表
     * @param $params
     * @since: 2023/1/3 11:10
     * @author: Zhu
     */
    private function getDataList($params)
    {
        $uid  = session('user_auth.uid');
        $dataSql  = db('ads_book_material_data');
        $dataCount  = db('ads_book_material_data');

        if (isset($params['book_id'])) {
            $dataSql = $dataSql->where('book_id', $params['book_id']);
            $dataCount = $dataCount->where('book_id', $params['book_id']);
        }else{
            $bookList = db('ads_material_book')->order('sort', 'desc')->find();
            $dataSql = $dataSql->where('book_id', $bookList['id']);
            $dataCount = $dataCount->where('book_id', $bookList['id']);
        }
        if ($uid > 1) {
            $dataSql = $dataSql->where('uid', $uid);
            $dataCount = $dataCount->where('uid', $uid);
        }

        $dataPage = [
            'dataTotal' => $dataCount->count(),
            'dataPage' => isset($params['dataPage']) ? $params['dataPage'] : 0,
            'dataLimit' => isset($params['dataLimit']) ? $params['dataLimit'] : 30
        ];

        $dataList = $dataSql->order('create_time', 'desc')
            ->page($dataPage['dataPage'], $dataPage['dataLimit'])->select();

        $bookList = db('ads_material_book')->order('sort', 'desc')->select();
        foreach ($dataList as $k =>$v) {
            $books = array_column($bookList, null, 'id');
            $v['uname'] = db('member')->where('uid', $v['uid'])->value('username');
            $v['book_name'] = $books[$v['book_id']]['title']??'';
            $v['create_time'] = date('m-d H:i', $v['create_time']);
            $v['one_proportion'] = $v['income_one'] == 0 ? 0 : round($v['income_one'] / $v['consume'] * 100);
            $v['two_proportion'] = $v['income_two'] == 0 ? 0 : round($v['income_two'] / $v['consume'] * 100);
            $v['three_proportion'] = $v['income_three'] == 0 ? 0 : round($v['income_three'] / $v['consume'] * 100);
            $v['income_proportion'] = $v['income'] == 0 ? 0 : round($v['income'] / $v['consume'] * 100);
            $dataList[$k] = $v;
        }
        return ['list' => $dataList, 'page' => $dataPage];
    }

    /**
     * Notes: 获取版本列表
     * @param $params
     * @since: 2023/1/3 11:04
     * @author: Zhu
     */

    private function getReplaceList($params)
    {
        $uid  = session('user_auth.uid');
        $replaceSql  = db('replace_log');
        $replaceCount  = db('replace_log');
        if (isset($params['book_id'])) {
            $replaceSql = $replaceSql->where('book_id', $params['book_id']);
            $replaceCount = $replaceCount->where('book_id', $params['book_id']);
        }else{
            $bookList = db('ads_material_book')->order('sort', 'desc')->find();
            $replaceSql = $replaceSql->where('book_id', $bookList['id']);
            $replaceCount = $replaceCount->where('book_id', $bookList['id']);
        }
        if ($uid > 1) {
            $replaceSql = $replaceSql->where('uid', $uid);
            $replaceCount = $replaceCount->where('uid', $uid);

        }

        $repPage = [
            'repTotal' => $replaceCount->count(),
            'repPage' => isset($params['repPage']) ? $params['repPage'] : 0,
            'repLimit' => isset($params['repLimit']) ? $params['repLimit'] : 30
        ];
        $replaceList = $replaceSql->order('create_time', 'desc')
            ->page($repPage['repPage'], $repPage['repLimit'])->select();

        foreach ($replaceList as $k =>$v) {
            $v['uname'] = db('member')->where('uid', $v['uid'])->value('username');
            $v['create_time'] = date('m-d H:i', $v['create_time']);
            if ($v['choose'] == 2) {
                $v['choose_u'] = db('member')->where('uid', $v['choose_uid'])->value('username');
                $v['choose_time'] = date('m-d H:i', $v['choose_time']);
            }
            $replaceList[$k] = $v;
        }
        return ['list' => $replaceList, 'page' => $repPage];
    }

    /**
     * Notes: 获取文本列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since: 2023/1/3 11:03
     * @author: Zhu
     */
    private function getTxtLog($params)
    {
        $uid  = session('user_auth.uid');
        $txtSql = db('upload_txt_log');
        $txtCount = db('upload_txt_log');
        if (isset($params['book_id'])) {
            $txtSql = $txtSql->where('book_id', $params['book_id']);
            $txtCount = $txtCount->where('book_id', $params['book_id']);
        }else{
            $bookList = db('ads_material_book')->order('sort', 'desc')->find();
            $txtSql = $txtSql->where('book_id', $bookList['id']);
            $txtCount = $txtCount->where('book_id', $bookList['id']);
        }
        if ($uid > 1) {
            $txtSql = $txtSql->where('uid', $uid);
            $txtCount = $txtCount->where('uid', $uid);
        }
        $txtPage = [
            'txtTotal' => $txtCount->count(),
            'txtPage' => isset($params['txtPage']) ? $params['txtPage'] : 0,
            'txtLimit' => isset($params['txtLimit']) ? $params['txtLimit'] : 30,
        ];
        $txtLog = $txtSql->order('create_time', 'desc')
            ->page($txtPage['txtPage'], $txtPage['txtLimit'])->select();
        foreach ($txtLog as $k =>$v) {
            $v['uname'] = db('member')->where('uid', $v['uid'])->value('username') ?? '';
            $v['file_out'][] = db('replace_log')->where('txt_log_id', $v['id'])->column('file_out');
            $v['create_time'] = date('Y-m H:i', $v['create_time']);
            $txtLog[$k] = $v;
        }
        return ['list' => $txtLog, 'page' => $txtPage];
    }

    //素材相关
    private function bookMaterial(  $cate_type ) {
        $book_id = $this->book_id;
        $keyword = input('get.keyword');
        $uid     = session('user_auth.uid');
        // $guid    = input('get.uid', $uid);
        // if($guid == 0){
        //     $uids    = $this->getUids($uid);
        // }else{
        //     $uids    = [$guid];
        // }
        
        $create_uid    = input('get.uid',0);
        $uids    = $this->getUids($uid);
        
        $map = [
            "cate_type" => $cate_type,
            'uid' => ["in", $uids],
            "book_id" => $book_id
        ];
        if($create_uid != 0){
            $map['create_uid'] = $create_uid;
        }
       
        // dump($map);exit;
        if($keyword) {
            $map['content'] = ["like", "%$keyword%"];
        }
        // dump($map);exit;
        $pageSize = 50;
        $pagestr = input('get.page', 1); //翻页序号
        $order = "id desc";
        $map_sql = "1=1";
        $i = 1;
        $list = db('ads_book_material')->where($map)->order( $order )->where($map_sql)->paginate( $pageSize, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        foreach ($list as $k => $v) {
            $v['content']     =  str_replace(["\"", "'"],"”", htmlspecialchars_decode($v['content'], ENT_QUOTES ) );
            $v['content_zh']  =  $v['content'];
            $v['show_time']   =  date('m-d H:i', $v['create_time']);
            $v['content_zh2'] = douyin_str_format($v['content']);
            $v['num'] =  $i+($pageSize*($pagestr-1)); //序号
            if(input('get.atest')){
                dump($v);exit;
            }
            $i++;
            $list[$k] = $v;
        }
        $page = $list->render();
        $create_uids =  db('ads_book_material')->group('create_uid')->column("create_uid");
        $userlist3 = db('member')->where( "uid", "in", $create_uids )->column("uid,username"); //工作台显示当前账号子账号下的
        $this->assign(compact('keyword', 'list', 'page', 'userlist3'));
    }

    //选用接口
    public function selection(){
        $id = input('param.id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $uid     = session('user_auth.uid');
        $map = [];
		$map['id'] = array('IN', $id);
        db('ads_book_material')->where($map)->update(['selection_uid' => $uid,'selection_time' => time()]);
        return $this->success("已选用");
    }

    public function add() {
        // return $this->error("失败！");
        if(IS_POST){
            $post = input('post.');
           
            if( empty($post['id']) ){
                $post['uid'] = session('user_auth.uid');
                $post['create_uid'] = session('user_auth.uid'); //创建人是自己
                
                $post['create_time'] = time();
                // 文案批量上传
                if(isset($post['ebook'])&&$post['ebook']){
                    if( in_array($post['cate_type'], ['douyin_text', 'weibo_text'])){
                        $list = $this->uploadDownTxt->read_txt_3($post['ebook']);
                        // dump($list);exit;
                    }else{
                        $list = $this->uploadDownTxt->read_txt($post['ebook']);
                    }
                    unset($post['ebook']);
                    unset($post['id']);
                    $insertData = [];
                    foreach ($list as $content) {
                        $insertData[] = array_merge($post, ['content'=>$content]);
                    }
                    // 数据太多 分批插入
                    $list = array_chunk($insertData, 1000);
                    foreach($list as $saveitem){
                        db('ads_book_material')->insertAll($saveitem);
                    }
                }else{
                    //如果是媒体文件 ，有http有英文逗号分新的一条
                    if(stristr($post['content'], 'http') && stristr($post['content'], ',')){
                        $contents = explode(',', $post['content']);
                        $titles   =  [];
                        $post['title'] = $post['title']??"";
                        if(isset($post['title']) && stristr($post['title'], ',')){
                            $titles  =  explode(',', $post['title']);
                        }
                        $covers   =  [];
                        $post['cover'] = $post['cover']??"";
                        if(isset($post['cover']) && stristr($post['cover'], ',')){
                            $covers  =  explode(',', $post['cover']);
                        }
                        unset($post['id']);
                        $insertData = [];
                        foreach ($contents as $k=>$content) {
                            if(empty($content)) continue;
                            $title        = $titles[$k]??$post['title'];
                            $cover        = $covers[$k]??$post['cover'];
                            $insertData[] = array_merge($post, ['content'=>$content, 'title'=> $title, 'cover'=> $cover]);
                        }
                        // dump($insertData);exit;
                        db('ads_book_material')->insertAll($insertData, true);
                        $id = db('ads_book_material')->getLastInsID();
                        action_log2($id, $post['cate_type']);
                    }else{
                        //文案单条上传
                        $id = db('ads_book_material')->insertGetId($post);
                        action_log2($id, $post['cate_type']);
                    }
                }
            }else{
                $post['update_time'] = time();
                db('ads_book_material')->update($post);
                action_log2($post['id'], $post['cate_type']);
            }
            return $this->success("添加成功！");
        }
        return $this->error("失败！");
    }
    
    public function del() {
		$id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $map = [];
		$map['id'] = array('IN', $id);
        $cate_type = db('ads_book_material')->where($map)->value('cate_type');
		$result    = db('ads_book_material')->where($map)->delete();
        action_log2($id, $cate_type);
		if (false !== $result) {
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}


    //pid下级的全部uid
    public function getUids($uid) {
        $members = db("member")->column('uid as id,pid','uid');
        $pid_sub = $this->recursion($members, $uid);
        $pid_sub_ids = array_column($pid_sub, 'uid');
        $uids  = array_merge($pid_sub_ids, [$uid]);
        return $uids;
    }

    /**
    * 根据父级id查找子级数据
    * @param $data     要查询的数据
    * @param int $pid 父级id
    */
    private function recursion($data, $pid = 0) {
        static $child = [];   // 定义存储子级数据数组
         foreach ($data as $key => $value) {
             if ($value['pid'] == $pid) {
                 $child[] = $value;   // 满足条件的数据添加进child数组
                 unset($data[$key]);  // 使用过后可以销毁
                 $this->recursion($data, $value['id']);   // 递归调用，查找当前数据的子级
             }
         }
         return $child;
    }

    //用户下拉
    private function getUserList() {
        $uid  = session('user_auth.uid');
        $uids = $this->getUids($uid);
        $map = [];
        if(session('user_auth.group') != 999){
            $map["uid"] = ["in", $uids];
        }
        $userlist2 = db('member')->where( $map  )->column("uid,username"); //工作台显示当前账号子账号下的
        $userlist  = db('member')->column("uid,username"); // 公众库用户列表显示全部的
        $userlist3 = []; //给个默认值 防止报错
        $this->assign(compact('userlist','userlist2', 'uid','userlist3'));
        return $userlist2;
    }

    /**
     * Notes:txt上传记录
     * @author: Zhu
     * @since: 2022/12/5 17:02
     */
    public function addTxtLog()
    {
        if(IS_POST) {
            $uid = session('user_auth.uid');
            if (IS_POST) {
                $post = input('post.');
                $post['uid'] = $uid;
            }
            $post['create_time'] = time();
            $post['name'] = '标本-'.$post['name'] ? '标本-'.$post['name'] : '标本-'.basename($post['file_path']);

            Db::startTrans();
            // 校验编码
            $file = file_get_contents($post['file_path']);
            $encoding = mb_detect_encoding($file, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
            if ($encoding != 'UTF-8') {
                $path =  './uploads'.DIRECTORY_SEPARATOR.'attachment'.DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR;
                $file_out = $path.md5(microtime(true)).".txt";
                $file = mb_convert_encoding($file, "UTF-8", $encoding);
                file_put_contents($file_out, $file);
                $post['file_path'] = $file_out;
            }
            $txtId = db('upload_txt_log')->insertGetId($post);
            $generatingDirectory = self::generatingDirectory($post['file_path'], $txtId);
            $savedata = array_chunk($generatingDirectory,1000); // 防止文件过大 分割数组
            foreach($savedata as $saveitem){
                db('ads_book_directory')->insertAll($saveitem);
            }
            Db::commit();
            return $this->success("成功！");

        }
        return $this->error("失败！");

    }

    /**
     * Notes: 生成章节目录以及内容
     * @param $filepath
     * @param $bookId
     * @return array
     * @since: 2022/12/9 14:20
     * @author: Zhu
     */
    private function generatingDirectory($filepath, $txtId)
    {
        $section=[];
        $i=0;
        $file = fopen($filepath,"r");
        $sort = 1;
        $num = 1;
        if ($file) {
            // 生成目录信息
            while(!feof($file)) {
                $line = fgets($file);
                $i += 1;
                if (strlen($line) < 3) {
                    continue;
                }
                $rt = preg_match_all("/第\s*[一二两三四五六七八九十○零百千万亿0-9１２３４５６７８９０]{1,50}\s*(章|话|节)[\s\S]*?(?:(?=\s*第\s*[一二两三四五六七八九十○零百千万亿0-9１２３４５６７８９０]{1,50}\s*(章|话|节))|$)/", $line, $arr);
                if (!$rt) {
                    continue;
                }

                $section[] = [
                    'txt_id' => $txtId,
                    'title'=>trim($arr[0][0]),
                    'line'=>$i,
                    'sort' => $sort
                ];
                $sort ++;
            }

            $myfile = file($filepath);
            foreach ($section as $k => $v) {
                $content = '';
                if (isset($section[$k+1])) {
                    for ($i = $v['line'] -1; $i < $section[$k+1]['line'] - 1; $i++) {
                        $content.= $myfile[$i] . '<br>';
                    }
                } else {
                    for ($i = $v['line'] -1; $i < count($myfile); $i++) {
                        $content.= $myfile[$i] . '<br>';
                    }
                }
                if (strlen($content) < 60) { // 防止章节重复
                    unset($section[$k]);
                    continue;
                }
                $section[$k]['num'] = $num;
                $section[$k]['content'] = $content;
                $section[$k]['create_time'] = time();
                $num ++;
            }
        }

        return $section;
    }

    /**
     * Notes: 版本评级、选用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @author: Zhu
     * @since: 2022/12/7 14:56
     */
    public function versionEdit()
    {
        if(IS_POST){
            $params = input('post.');
            if (isset($params['choose'])) {
                $params['choose_uid'] = session('user_auth.uid');
                $params['choose_time'] = time();
            }
            $params['update_time'] = time();
            db('replace_log')->where('id', $params['id'])->update($params);
            return $this->success("修改成功！");
        }
        return $this->error("修改失败！");
    }

    /**
     * Notes: 修改文本
     * @throws Exception
     * @throws \think\exception\PDOException
     * @author: Zhu
     * @since: 2022/12/9 15:13
     */
    public function editSynopsis()
    {
        $validate = new Validate([
            'id' => 'require|number'
        ],[
            'id.require' => '缺少文本id'
        ]);
        $params = request()->param();
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }

        $params['update_time'] = time();
        $edit = db('upload_txt_log')->where('id', $params['id'])->update($params);
        if ($edit) {
            return $this->success("修改成功！");
        }
        return $this->error("修改失败！");
    }

    /**
     * Notes: 新增数据
     * @return null
     * @since: 2022/12/31 15:15
     * @author: Zhu
     */
    public function addMaterualData()
    {
        if(IS_POST) {
            $post = input('post.');
            $validate = new Validate([
                'book_id'  => 'require',
                'consume' => 'require|float',
                'price' => 'require|float',
                'point' => 'float',
                'rate' => 'float',
                'income' => 'float',
                'income_one' => 'float',
                'income_two' => 'float',
                'income_three' => 'float',
            ],[
                'book_id.require' => '请选择书籍',
                'consume.require' => '请输入消耗',
                'price.require' => '请输入粉价',
                'consume.float' => '消耗必须是数值',
                'price.float' => '粉价必须是数值',
                'point.float' => '单点必须是数值',
                'rate.float' => '付费率必须是数值',
                'income.float' => '回收必须是数值',
                'income_one.float' => '回收必须是数值',
                'income_two.float' => '回收必须是数值',
                'income_three.float' => '回收必须是数值',
            ]);
            if (!$validate->check($post)) {
                return $this->error($validate->getError());
            }
            foreach ($post as $k => $v) {
                $post[$k] = trim($v);
            }
            if (isset($post['book_name']) && !empty($post['book_name'])) {
                $have = db('ads_material_book')->where('title', $post['book_name'])->find();
                if ($have) {
                    $post['book_id'] = $have['book_id'];
                } else {
                    $post['book_id'] = db('ads_material_book')->insertGetId([
                        'name' => '其他',
                        'title' =>  $post['book_name'],
                        'sort' => 100,
                        'create_time' => time()
                    ]);
                }

            }
            $post['create_time'] = time();
            $post['uid'] = session('user_auth.uid');
            $addMaterualData = db('ads_book_material_data')->insert($post);
            if ($addMaterualData) {
                return $this->success("成功！");
            }
            return $this->error("失败！");
        }
        return $this->error("失败！");
    }

    /**
     * Notes:删除数据
     * @return null
     * @throws Exception
     * @throws \think\exception\PDOException
     * @since: 2022/12/31 15:15
     * @author: Zhu
     */
    public function delMaterualData() {
        $id = $this->getArrayParam('id');
        $type = request()->get('type');
        if (empty($id) || empty($type)) {
            return $this->error("非法操作！");
        }
        switch ($type) {
            // 数据
            case 'data':
                db('ads_book_material_data')->whereIn('id', $id)->delete();
                return $this->success("删除成功！");
            // 文本
            case 'txt':
                db('upload_txt_log')->whereIn('id', $id)->delete();
                db('ads_book_directory')->whereIn('txt_id', $id)->delete();
                return $this->success("删除成功！");
            // 替换
            case 'replace':
                db('replace_log')->whereIn('id', $id)->delete();
                return $this->success("删除成功！");
        }

        return $this->error("删除失败！");
    }


}